#! /usr/bin/env python
# -*- coding: utf8 -*-

import zope.interface
import random
import base

class swapWords(object):
    zope.interface.implements(base.IAlgorithm)
    name = "swapWords"

    def __init__(self, node):
        if node.find("./parameters/includeFirst") != None:
            self.__includeFirst = node.find("./parameters/includeFirst").strip() == "True"
        else:
             self.__includeFirst = True

        if node.find("./parameters/includeLast") != None:
            self.__includeLast = node.find("./parameters/includeLast").strip() == "True"
        else:
             self.__includeLast = True

        self.__bOffset = 0
        if not self.__includeFirst:
            self.__bOffset = 1

        self.__eOffset = 0
        if not self.__includeLast:
            self.__lOffset = 1


    def __call__(self, string):
        words    = string.split(" ")

        if len(words) < self.__lOffset + self.__bOffset + 2:
            return string

        numWords = len(words)

        o = random.randint(self.__bOffset, numWords - 1 - self.__bOffset)
        d = random.randint(self.__bOffset, numWords - 1 - self.__bOffset)

        if o != d:
            words[o], words[d] = words[d], words[o]

        return " ".join(words)

__plugins__ = (swapWords, )
